# -*- coding: gb2312

import os
import httplib
import urllib
import urllib2
import httplib2
import CookieClient

DEFAULT_MAX_REDIRECTS = httplib2.DEFAULT_MAX_REDIRECTS

class Browser(httplib2.Http):

    def __init__(self, cache=None, timeout=None, proxy_info=None,
                 ca_certs=None, disable_ssl_certificate_validation=False):
        """
        just add a member to the httplib2.Http library as "_cookie" which store
        the cookie from the server response.
        This member will be add to the request header as name "Cookie:"
        """
        self._cookie = CookieClient.CookieClient()
        super(Browser, self).\
        __init__(cache=cache, timeout=timeout, proxy_info=proxy_info, ca_certs=ca_certs,
                 disable_ssl_certificate_validation=disable_ssl_certificate_validation)
    #end of __init__

    def request(self, uri, method="GET", body=None, headers=None,
                redirections=DEFAULT_MAX_REDIRECTS, connection_type=None):
        """
        Library Browser's method "request" inherits method from httplib2. It's just extend
        function of cookie handle. Through overwrite request method, it will be transparent
        to user about how to store and add cookie to the header
        """
        if not self._cookie.items():
            headers = headers
        #TODO: finish the cookie handler

        resp, content = super(Browser, self).\
        request(uri, method=method, body=body, headers=headers,
                redirections=redirections, connection_type=connection_type)
        self._cookie.load(resp["set-cookie"])

    def _add_cookie_headers(self, ):
        #TODO: finish the cookie handle design, maybe I should use the reference of cookielib
        pass


